﻿using System;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DllShepherd.SilverlightGoogleMaps.Web.Resources;

namespace DllShepherd.SilverlightGoogleMaps.Web
{
    public partial class GoogleMapsApi3TestPage : Page
    {
        private void SaveSilverlightDeploymentSettings(Literal litSettings)
        {
            NameValueCollection appSettings = ConfigurationManager.AppSettings;

            var parameters = new StringBuilder();
            parameters.Append("<param name=\"InitParams\" value=\"");

            var settingCount = appSettings.Count;
            for (int index = 0; index < settingCount; index++)
            {
                parameters.Append(appSettings.GetKey(index));
                parameters.Append("=");
                parameters.Append(HttpUtility.UrlEncode(appSettings[index]));
                parameters.Append(",");
            }
            SaveSilverlightResourcesSettings(parameters);

            parameters.Remove(parameters.Length - 1, 1);
            parameters.Append("\" />");

            litSettings.Text = parameters.ToString();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            SaveSilverlightDeploymentSettings(ParamInitParams);
        }

        private void SaveSilverlightResourcesSettings(StringBuilder parameters)
        {
            var culture = ConfigurationManager.AppSettings["Culture"] ?? Thread.CurrentThread.CurrentCulture.Name;
            var filename = Server.MapPath(String.Format("Resources\\StringsResource.{0}.resx", culture));
            if (!File.Exists(filename))
                filename = Server.MapPath("Resources\\StringsResource.resx");
            TextReader tr = new StreamReader(filename);

            parameters.Append(StringsResourceName.Name);
            parameters.Append("=");
            parameters.Append(HttpUtility.UrlEncode(tr.ReadToEnd()));
            parameters.Append(",");

            tr.Close();
        }
    }
}